// import { useMemberStore } from '@/stores'

const baseUrl = 'https://music.xkbk.top/'

/**
 * 请求拦截器
 */
const httpInterceptor = {
  /**
   * 拦截前触发
   * @param options UniApp.RequestOptions
   */
  invoke(options: UniApp.RequestOptions) {
    // 非http开头拼接Url
    if (!options.url.startsWith('http')) {
      options.url = baseUrl + options.url
    }

    options.header = {
      ...options.header,
    }
    //设置请求超时
    options.timeout = 10000
    //设置token
    // const memberStore = useMemberStore()
    // const token = memberStore.profile?.token
    // if (token) {
    //   options.header.Authorization = token
    // }
  },
}
//配置拦截器
uni.addInterceptor('request', httpInterceptor)
uni.addInterceptor('uploadFile', httpInterceptor)

export const http = (options: UniApp.RequestOptions) => {
  return new Promise<any>((resolve, reject) => {
    uni.showLoading({
      title: '加载中...',
    })
    uni.request({
      ...options,
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          uni.hideLoading()
          resolve(res.data)
        } else if (res.statusCode === 401) {
          reject(res)
        } else {
          //其它报错-> 轻提示
          // uni.showToast({
          //   title: (res.data as Data<T>).msg || '请求错误',
          //   icon: 'none',
          // })
          reject(res)
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '网络错误，换个网络试试',
          icon: 'none',
        })
        reject(err)
      },
    })
  })
}
